import os
import cv2
import numpy as np

# 为预览生成一个示例底图
h, w = 720, 1280
base = np.zeros((h, w, 3), dtype=np.uint8)
cv2.putText(base, "Demo Frame", (40, h//2), cv2.FONT_HERSHEY_SIMPLEX, 2, (120, 200, 255), 3)

# 直接复制 hand_arm.py 中的右侧面板函数以避免导入复杂依赖
# 需要 put_chinese_text / put_label_box 的简化版本（预览使用英文/数字即可）

def put_chinese_text(img, text, position, font_size=22, color=(255, 255, 255)):
    # 预览环境用 OpenCV 英文字体简化显示
    cv2.putText(img, text, position, cv2.FONT_HERSHEY_SIMPLEX, font_size/32.0, color, 2)
    return img


def put_label_box(img, text, position, font_size=22, text_color=(255, 255, 255), box_color=(0, 0, 0)):
    x, y = position
    pad_x, pad_y = 6, 6
    # 估算文本宽度
    (tw, th), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, font_size/32.0, 2)
    cv2.rectangle(img, (x - pad_x, y - th - pad_y), (x + tw + pad_x, y + pad_y), box_color, -1)
    cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_SIMPLEX, font_size/32.0, text_color, 2)
    return img


def draw_right_panel(frame: np.ndarray, controller_logs, shoulder_deg, elbow_deg, wrist_deg, openness, panel_width: int = 360) -> np.ndarray:
    h, w = frame.shape[:2]
    full = np.zeros((h, w + panel_width, 3), dtype=np.uint8)
    full[:, :w] = frame

    x0 = w
    cv2.rectangle(full, (x0, 0), (x0 + panel_width - 1, h - 1), (40, 40, 40), -1)

    y = 12
    full = put_label_box(full, "角度与开合", (x0 + 12, y), font_size=22, text_color=(255,255,255), box_color=(0,0,0))
    y += 36
    s_txt = f"{shoulder_deg:.1f}°" if shoulder_deg is not None else "N/A"
    e_txt = f"{elbow_deg:.1f}°" if elbow_deg is not None else "N/A"
    w_txt = f"{wrist_deg:.1f}°" if wrist_deg is not None else "N/A"
    full = put_chinese_text(full, f"右肩角度: {s_txt}", (x0 + 18, y), 22, (200, 255, 200))
    y += 28
    full = put_chinese_text(full, f"右肘角度: {e_txt}", (x0 + 18, y), 22, (200, 255, 200))
    y += 28
    full = put_chinese_text(full, f"右腕角度: {w_txt}", (x0 + 18, y), 22, (200, 255, 200))
    y += 28
    full = put_chinese_text(full, f"右手张开度: {openness:.1f}%", (x0 + 18, y), 22, (0, 255, 255))

    y += 40
    full = put_label_box(full, "指令控制日志", (x0 + 12, y), font_size=22, text_color=(255,255,255), box_color=(0,0,0))
    y += 34

    logs = controller_logs[-12:] if controller_logs else []
    if not logs:
        full = put_chinese_text(full, "暂无日志", (x0 + 18, y), 20, (180, 180, 180))
    else:
        for item in logs:
            ok_flag = "OK" if item.get("ok") else "ERR"
            ts = item.get("ts", "")
            summary = item.get("summary", "")
            color = (0, 255, 0) if ok_flag == "OK" else (0, 0, 255)
            full = put_chinese_text(full, f"{ts} [{ok_flag}] {summary}", (x0 + 18, y), 18, color)
            y += 24
            if y > h - 24:
                break

    return full


# 伪造日志数据用于预览
controller_logs = [
    {"ts": "12:00:01", "ok": True,  "summary": "2:45 3:80 4:10"},
    {"ts": "12:00:12", "ok": False, "summary": "publish fail"},
    {"ts": "12:00:20", "ok": True,  "summary": "2:48 3:78 4:12"},
    {"ts": "12:01:00", "ok": True,  "summary": "2:50 3:80 4:15"},
]

# 角度与开合示例
frame = draw_right_panel(base, controller_logs, shoulder_deg=42.0, elbow_deg=75.0, wrist_deg=10.0, openness=86.6)

out_dir = os.path.dirname(__file__)
img_path = os.path.join(out_dir, "ui_panel_preview.jpg")
cv2.imwrite(img_path, frame)

html_path = os.path.join(out_dir, "ui_panel_preview.html")
with open(html_path, "w", encoding="utf-8") as f:
    f.write("""
<!doctype html>
<html lang=zh-cn>
  <head>
    <meta charset="utf-8" />
    <title>UI预览 - 右侧信息面板</title>
    <style>body{font-family:system-ui,Segoe UI,Helvetica,Arial; margin:20px;} img{max-width:100%; border:1px solid #ccc;} .desc{color:#555; margin-bottom:12px;}</style>
  </head>
  <body>
    <h2>右侧信息面板预览</h2>
    <div class="desc">左侧为原始图像，右侧为新增面板，显示角度、开合度与指令日志。</div>
    <img src="ui_panel_preview.jpg" alt="UI预览" />
  </body>
</html>
""")

print("预览已生成:", html_path)